﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.IO;

public class CellCenterCollate : ICollateStrategy
{
    nLayerOrder _StartOrder = nLayerOrder.Decos;

    public void ReOrder(nLayerOrder startOrder, ref List<ObjectBase> unitobjects)
    {
        for (int i = 0; i < unitobjects.Count; ++i)
        {
            OBOrder(_StartOrder, unitobjects[i]);
        }
    }


    public void OBOrder(nLayerOrder startOrder, ObjectBase ob)
    {
        Vector3 pos = ob._WorldPos;

        UnitObject uo = (UnitObject)ob;

        string uoname = Path.GetFileNameWithoutExtension(uo._unitData._res_name);

        if (uo._unitData._pivot == 'r')
            GetTopCell(ref pos, ob._rgc._Data._sec);
        else if (uo._unitData._pivot == 'l')
            GetBottomCell(ref pos, ob._rgc._Data._sec);

        ////int x = Mathf.RoundToInt(pos.x / (ZoneCfg.RhombusMin / 2));
        ////int y = Mathf.RoundToInt(pos.y / (ZoneCfg.RhombusMin / ZoneCfg.RhombusFactor / 2));

        ////int offx = x * x;
        ////int offy = y * y;
        ////int offsetx = (offx) * 10 + (offy) * 10 + offy;

        ////
        ////ob.SetSortingOrder((int)startOrder - (offsetx));

        SetUOLayer(pos, uo);
    }

    #region 根据Order来排序
    void SetUOLayer(Vector3 pos, UnitObject uo)
    {
        int order = GetRoundOrder(pos);

        int orderoffset = 0;

        string uoname = Path.GetFileNameWithoutExtension(uo._unitData._res_name);

        switch (uo._unitData._UnitType)
        {
            case nUnitType.Wall:
                if (uo._unitData._pivot == 'l')
                    orderoffset = 1;
                else if (uo._unitData._pivot == 'r')
                    orderoffset = 3;
                else
                    Debug.LogError("uo._unitData._pivot == null");
                break;
            case nUnitType.Decoration:
                    orderoffset = 2;
                break;
        }

        uo.SetSortingOrder((int)_StartOrder - (order) * 5 + orderoffset);

    }

    static nRhombusVBOData vbo = new nRhombusVBOData(ZoneCfg.RhombusMin, ZoneCfg.RhombusMin / ZoneCfg.RhombusFactor);

    int GetRoundOrder(Vector3 pos)
    {
        int order = ((LayerObject)ZoneManager._Groud[0]).GetClosePointOrder(pos, vbo);

        return order;
    }
    #endregion

    void GetTopCell(ref Vector3 worldpos, int sec)
    {
        worldpos.x += (ZoneCfg.RhombusMin / 2) * (sec - 1);
        worldpos.y += (ZoneCfg.RhombusMin / ZoneCfg.RhombusFactor) * (sec - 1);
    }

    void GetBottomCell(ref Vector3 worldpos, int sec)
    {
        worldpos.x += (ZoneCfg.RhombusMin / 2) * (sec - 1);
        worldpos.y -= (ZoneCfg.RhombusMin / ZoneCfg.RhombusFactor) * (sec - 1);
    }
}
